package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.user.client.UserFeignClient;
import com.sun.javafx.collections.MappingChange;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: Mr.Cao
 * @DateTime: 2021/10/21 14:58
 * BMW F750GS
 **/
@RestController
@RequestMapping("api/order")
public class OrderApiController {

    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 去结算页面,做数据的回显,
     * */
    @GetMapping("/trade")
    public Map trade(HttpServletRequest request){
       Map map =  orderService.trade(request);
        return map;
    }
    /**
     *
     *提交订单
     */
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, String tradeNo
            , HttpServletRequest request) {
        //获取用户Id
        String userId = AuthContextHolder.getUserId(request);
        //判断是否存在交易号
        if (StringUtils.isEmpty(tradeNo)) {
            return Result.fail().message("订单错误,没有交易号");
        }else {
            //从缓存中获取订单号
            Object no = redisTemplate.opsForValue().get("tradeNo:" + userId);
            if (StringUtils.isEmpty(no)){
                //缓存中不存在交易号
                return Result.fail().message("订单错误,非正常交易号");
            }else {
                //判断交易号是否正确
                if (tradeNo.equals(no)){
                    return Result.fail().message("订单错误,交易号不正确");
                }
            }
        }
        //删除交易号
        redisTemplate.delete("tradeNo:" + userId);
        //校验库存
            //获取订单商品集合
            List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            boolean isHave = orderService.hasStock(orderDetail);
            if(!isHave){
                //库存不足
                return Result.fail().message(orderDetail.getSkuName() + "[库存不足]");
            }
        }
        return Result.ok();
    }
}
